package com.cskaoyan.market.admin.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.cskaoyan.market.admin.service.AdminCouponService;
import com.cskaoyan.market.admin.service.MarketAdminCouponService;
import com.cskaoyan.market.admin.service.impl.AdminCouponServiceImpl;
import com.cskaoyan.market.admin.service.impl.MarketAdminCouponServiceImpl;
import com.cskaoyan.market.db.domain.MarketCoupon;
import com.cskaoyan.market.db.domain.MarketCouponUser;
import com.cskaoyan.market.util.HttpUtil;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.util.StringUtil;

/**
 * @author James
 * @since 2023/03/21 22:59
 */
@WebServlet("/admin/coupon/*")
public class AdminCouponController extends HttpServlet {
    MarketAdminCouponService marketAdminCouponService = new MarketAdminCouponServiceImpl();
    private AdminCouponService adminCouponService = new AdminCouponServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/coupon/", "");
        if ("update".equals(op)) {
            update(req, resp);
        } else if ("delete".equals(op)) {
            delete(req, resp);

        } else if ("create".equals(op)) {
            createCoupon(req, resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/coupon/", "");
        if ("list".equals(op)) {
            list(req, resp);
        } else if ("listuser".equals(op)) {
            listuser(req, resp);
        }
    }

    private void listuser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String pageParam = req.getParameter("page");
        String limitParam = req.getParameter("limit");
        String name = req.getParameter("name");
        String type = req.getParameter("type");
        String status = req.getParameter("status");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        String couponIdParam = req.getParameter("couponId");
        // 判断必要的数据
        if (StringUtil.isEmpty(pageParam) || StringUtil.isEmpty(limitParam)) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
        }
        // 给默认值
        if (StringUtil.isEmpty(sort)) {
            sort = "add_time";

        }
        if (StringUtil.isEmpty(order)) {
            order = "desc";
        }
        int limit = 0;
        int page = 0;
        int couponId = 0;
        try {
            limit = Integer.parseInt(limitParam);
            page = Integer.parseInt(pageParam);
            couponId = Integer.parseInt(couponIdParam);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        List<MarketCouponUser> list =
                marketAdminCouponService.getUserListByCouponId(page, limit, couponId, sort, order);
        if (list == null) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgumentValue()));
        } else {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.okList(list)));
        }
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String pageParam = req.getParameter("page");
        String limitParam = req.getParameter("limit");
        String name = req.getParameter("name");
        String type = req.getParameter("type");
        String status = req.getParameter("status");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        // 判断必要的数据
        if (StringUtil.isEmpty(pageParam) || StringUtil.isEmpty(limitParam)) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
        }
        // 给默认值
        if (StringUtil.isEmpty(sort)) {
            sort = "add_time";

        }
        if (StringUtil.isEmpty(order)) {
            order = "desc";
        }
        int limit = 0;
        int page = 0;

        try {
            limit = Integer.parseInt(limitParam);
            page = Integer.parseInt(pageParam);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        // 调用Service
        List<MarketCoupon> marketCoupons = marketAdminCouponService.list(page, limit, name, type, status, sort, order);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.okList(marketCoupons)));

    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String requestBody = HttpUtil.getRequestBody(req);

        String addTime = JacksonUtil.parseString(requestBody, "addTime");
        int days = JacksonUtil.parseInteger(requestBody, "days");
        boolean deleted = JacksonUtil.parseBoolean(requestBody, "deleted");
        int discountParam = JacksonUtil.parseInteger(requestBody, "discount");
        Double discount = Double.valueOf(discountParam);
        int goodsType = JacksonUtil.parseInteger(requestBody, "goodsType");
        List<Integer> goodsValue = JacksonUtil.parseIntegerList(requestBody, "goodsValue");
        int id = JacksonUtil.parseInteger(requestBody, "id");
        Integer limit = JacksonUtil.parseInteger(requestBody, "limit");
        String min = JacksonUtil.parseString(requestBody, "min");
        String name = JacksonUtil.parseString(requestBody, "name");
        Integer status = JacksonUtil.parseInteger(requestBody, "status");
        String tag = JacksonUtil.parseString(requestBody, "tag");
        Integer timeType = JacksonUtil.parseInteger(requestBody, "timeType");
        Integer total = JacksonUtil.parseInteger(requestBody, "total");
        Integer type = JacksonUtil.parseInteger(requestBody, "type");
        String updateTime = JacksonUtil.parseString(requestBody, "updateTime");

        if (StringUtils.isEmpty(name)) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        marketAdminCouponService.delete(days, deleted, discount, goodsType, goodsValue, id, limit, min, name, status,
                tag, timeType, total, type, updateTime);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok()));

    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        String addTime = JacksonUtil.parseString(requestBody, "addTime");
        int days = JacksonUtil.parseInteger(requestBody, "days");
        boolean deleted = JacksonUtil.parseBoolean(requestBody, "deleted");
        int discountParam = JacksonUtil.parseInteger(requestBody, "discount");
        Double discount = Double.valueOf(discountParam);
        int goodsType = JacksonUtil.parseInteger(requestBody, "goodsType");
        List<Integer> goodsValue = JacksonUtil.parseIntegerList(requestBody, "goodsValue");
        int id = JacksonUtil.parseInteger(requestBody, "id");
        Integer limit = JacksonUtil.parseInteger(requestBody, "limit");
        String min = JacksonUtil.parseString(requestBody, "min");
        String name = JacksonUtil.parseString(requestBody, "name");
        Integer status = JacksonUtil.parseInteger(requestBody, "status");
        String tag = JacksonUtil.parseString(requestBody, "tag");
        Integer timeType = JacksonUtil.parseInteger(requestBody, "timeType");
        Integer total = JacksonUtil.parseInteger(requestBody, "total");
        Integer type = JacksonUtil.parseInteger(requestBody, "type");
        String updateTime = JacksonUtil.parseString(requestBody, "updateTime");

        if (StringUtils.isEmpty(name)) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        MarketCoupon marketCoupon = marketAdminCouponService.update(days, deleted, discount, goodsType, goodsValue, id,
                limit, min, name, status, tag, timeType, total, type, updateTime);
        HashMap<Object, Object> data = getResponseBody(marketCoupon);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok(data)));

    }

    private HashMap<Object, Object> getResponseBody(MarketCoupon marketCoupon) {
        HashMap<Object, Object> data = new HashMap<>();
        data.put("days", marketCoupon.getDays());
        data.put("deleted", marketCoupon.getDeleted());
        data.put("discount", marketCoupon.getDiscount());
        data.put("goodsType", marketCoupon.getGoodsType());
        data.put("goodsValue", marketCoupon.getGoodsValue());
        data.put("id", marketCoupon.getId());
        data.put("limit", marketCoupon.getLimit());
        data.put("min", marketCoupon.getMin());
        data.put("name", marketCoupon.getName());
        data.put("status", marketCoupon.getStatus());
        data.put("tag", marketCoupon.getTag());
        data.put("timeType", marketCoupon.getTimeType());
        data.put("total", marketCoupon.getTotal());
        data.put("type", marketCoupon.getType());
        data.put("updateTime", marketCoupon.getUpdateTime());

        return data;
    }

    private void getCouponList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String pageParam = req.getParameter("page");
        String limitParam = req.getParameter("limit");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        if (StringUtils.isEmpty(pageParam) || StringUtils.isEmpty(limitParam)) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgumentValue()));
            return;
        }
        if (StringUtils.isEmpty(sort)) {
            sort = "add_time";
        }
        if (StringUtils.isEmpty(order)) {
            order = "desc";
        }
        int page = 0;
        int limit = 0;
        try {
            page = Integer.parseInt(pageParam);
            limit = Integer.parseInt(limitParam);
        } catch (Exception e) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        List<MarketCoupon> list = adminCouponService.getCouponList(page, limit, sort, order);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.okList(list)));
    }

    private void createCoupon(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        MarketCoupon data = null;
        try {
            data = objectMapper.readValue(requestBody, MarketCoupon.class);
        } catch (Exception e) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.fail(402, "参数值不对")));
            return;
        }
        int code = adminCouponService.createCoupon(data);
        if (code != 1) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgumentValue()));
        }
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok(data)));
    }
}